package com.wfyvv.fast.common.core.valid;

import com.alibaba.fastjson.JSON;
import com.wfyvv.fast.common.core.ServiceException;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 数据校验
 *
 * @author fengyu.wang
 * @since 2018-05-29 14:39:42
 */
public abstract class Assert {

    private Assert() {
        throw new IllegalStateException("Utility class");
    }

    public static void isBlank(String str, String message) {
        if (StringUtils.isBlank(str)) {
            fail(message);
        }
    }

    public static void isNotBlank(String str, String message) {
        if (StringUtils.isNotBlank(str)) {
            fail(message);
        }
    }

    public static void isNull(Object object, String message) {
        if (object == null) {
            fail(message);
        }
    }

    public static void notNull(Object object, String message) {
        if (object != null) {
            fail(message);
        }
    }

    public static void equals(Object a, Object b, String message) {
        if (!Objects.equals(a, b)) {
            throw new ServiceException(message);
        }
    }

    public static void assertTrue(boolean condition, String message) {
        if (!condition) {
            fail(message);
        }

    }

    private static void fail(String message) {
        throw new ServiceException(message);
    }

    public static void assertJSON(String jsonStr, String message) {
        try {
            JSON.parseObject(jsonStr);
        } catch (Exception e) {
            throw new ServiceException(message);
        }
    }
}
